package com.hp.service.impl;

import com.hp.dao.CartDao;
import com.hp.dao.GoodDao;
import com.hp.entity.Cart;
import com.hp.entity.Good;
import com.hp.entity.User;
import com.hp.service.ICartService;
import com.hp.vo.CartVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiuQiang
 * @Date: 2021/11/8 14:56
 * @Description
 */
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartDao cartDao;
    @Autowired
    private GoodDao goodDao;

    @Override
    public List<CartVo> addCart(Integer goodId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Cart> cartList = cartDao.selectCartsByAll(goodId,user.getId());
        if (cartList.size() > 0){
            //如果添加的商品在购物车中存在，则数量+1
            cartDao.updateCartsByAmount(cartList.get(0).getAmount() + 1,goodId, user.getId());
        }else {
            if(goodId != 0){
                Cart cart = new Cart();
                cart.setGoodId(goodId);
                cart.setUserId(user.getId());
                cartDao.addCart(cart);
            }else {
                return null;
            }
        }
        List<Cart> cartList2 = cartDao.selectCartsByAll(0,user.getId());
        return copyBean(cartList2,user);
    }

    @Override
    public int updateCartsByAmountSubtractAndAdd(Integer subtract, Integer add, Integer id) {
        return cartDao.updateCartsByAmountSubtractAndAdd(subtract,add,id);
    }

    @Override
    public int deleteCartById(Integer id) {
        return cartDao.deleteCartById(id);
    }

    @Override
    public int deleteCartByUserId(Integer userId) {
        return cartDao.deleteCartByUserId(userId);
    }

    private List<CartVo> copyBean(List<Cart> cartList,User user){
        List<CartVo> cartVoList = new ArrayList<>();
        for (Cart cart : cartList){
            CartVo cartVo = new CartVo();
            BeanUtils.copyProperties(cart,cartVo);
            Good good = goodDao.findGoodById(cart.getGoodId());
            cartVo.setGood(good);
            cartVo.setTotal(cart.getAmount() * good.getPrice());
            cartVoList.add(cartVo);
        }
        return cartVoList;
    }
}
